import { Avatar, Icon, Menu, Spin } from 'antd';
import React, { useState } from 'react';
import { connect } from 'dva';
import HeaderDropdown from '../HeaderDropdown';
import ChangePwd from '@/components/AxHeader/ChangePwd/index';
import styles from './index.less';

/** 顶部用户下拉框 */
const AvatarDropdown = props => {
  const {
    dispatch,
    currentUser = {
      avatar: '',
      name: '',
    },
    collapse,
  } = props;
  const [pwdVisible, setPwdVisible] = useState(false);
  const [pwdValues, setPwdValues] = useState({ account: 'Bill' });

  const handleUpdatePwd = () => { };

  const handleMore = (key, items) => {
    const item = items[key];
    item && item.onClick && item.onClick();
  };

  const pwdMethods = {
    handleVisible: setPwdVisible,
    handleUpdate: handleUpdatePwd,
  };

  const operates = [{
    key: 'key',
    text: '修改密码',
    icon: 'key',
    onClick: () => setPwdVisible(true),
  }, {
    key: 'logout',
    text: '退出登录',
    icon: 'logout',
    onClick: () => {
      if (dispatch) {
        dispatch({
          type: 'login/logout',
        });
      }
      return;
    },
  }]
  
  if (collapse) {
    return operates;
  }

  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={({ key }) => handleMore(key, operates)}>
      {operates.map((i, idx) => (
        <Menu.Item key={idx}>
          <Icon type={i.icon} />
          {i.text}
        </Menu.Item>
      ))}
    </Menu>
  );

  return currentUser && currentUser.userName ? (
    <>
      <HeaderDropdown overlay={menuHeaderDropdown}>
        <span className={`${styles.action} ${styles.account}`}>
          <Avatar size="small" className={styles.avatar} src={currentUser.avatar} alt="avatar" />
          <span className={styles.name}>{currentUser.userName}</span>
        </span>
      </HeaderDropdown>
      {pwdVisible && <ChangePwd {...pwdMethods} visible={pwdVisible} values={pwdValues} />}
    </>
  ) : (
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8,
        }}
      />
    );
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(AvatarDropdown);
